package com.mlz.mlzmall.ui.activity.act.main;

import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.UserBean;
import com.mlz.mlzmall.custom.CustomButton;
import com.mlz.mlzmall.ui.activity.act.base.NetworkActivity;
import com.mlz.mlzmall.ui.activity.frag.main.HomeFragment;
import com.mlz.mlzmall.ui.activity.frag.main.ShoppingCartFragment;
import com.mlz.mlzmall.ui.inter.NetResponses;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.volley.volley.NetRequest;
import com.mlz.mlzmall.volley.volley.RequestListener;
import com.mlz.mlzmall.volley.volley.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * 功能描述：主界面
 * Created by benny on 2016/5/7.
 * ProjectName：mlzMall.
 */
public class MainActivity extends NetworkActivity implements NetResponses {

    private TextView cartSize;//显示购物车里的数量
    private CustomButton btnCart;//购物车
    private CustomButton btnHome;//首页
    private UserBean userBean;


    private HomeFragment home;
    private ShoppingCartFragment sCart;
    private FragmentTransaction ft;
    private int fTag;
    Intent intent;
    public static int flg;
    int type = 0;
    private Broad broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        setNetResponses(this);
        System.out.println("@@@onCreate");
        IntentFilter filter = new IntentFilter("ShoppingCartFragment");
        broadcastReceiver = new Broad();
        registerReceiver(broadcastReceiver, filter);

        ft = getFragmentManager().beginTransaction();
        home = new HomeFragment();
        sCart = new ShoppingCartFragment();
        sCart.setOnExitFragment(new ShoppingCartFragment.OnExitFragment() {
            @Override
            public void onClick() {
                if (btnCart.isSelected()) {
                    ft = getFragmentManager().beginTransaction();
                    setBtn(true, false);
                    ft.hide(sCart);
                    ft.show(home);
                    ft.commit();
                    type = 0;
                }
            }

            @Override
            public void setCartTotal(String item) {
                if ("0".equals(item)) {
                    cartSize.setVisibility(View.GONE);
                } else {
                    cartSize.setVisibility(View.VISIBLE);
                    cartSize.setText(item);
                }
            }
        });
        ft.add(R.id.main_content, home);
        ft.add(R.id.main_content, sCart);
        ft.commit();
        tag = "MainActivity";
        initView();
        if (type == 0) {
            showFragment(1);
            setBtn(true, false);
        } else {
            showFragment(2);
            setBtn(false, true);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        intent = getIntent();
        sessionId = ACache.get(this).getAsString("sessionKeyLogin");
//        getShoppingCartNumber();
        if(type == 2){
            showFragment(2);
            setBtn(false, true);
            type = 0;
        }

    }

    protected void initView() {
        btnHome = (CustomButton) findViewById(R.id.home);
        btnCart = (CustomButton) findViewById(R.id.shoppingCart);
        btnHome.setBackgroundResource(R.drawable.tab_home);
        btnCart.setBackgroundResource(R.drawable.tab_shopping_cart);
        btnHome.setText("首页");
        btnCart.setText("购物车");
        cartSize = (TextView) findViewById(R.id.cartSize);
        btnHome.setOnClickListener(this);
        btnCart.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home:
                setBtn(true, false);
                showFragment(1);
                break;
            case R.id.shoppingCart:
                setBtn(false, true);
                showFragment(2);
                type = 0;
                break;
            default:
                showToast("程序错误");
                break;
        }
    }

    private void showFragment(int i) {
        ft = getFragmentManager().beginTransaction();
        switch (i) {
            case 1:
                ft.show(home);
                ft.hide(sCart);
                break;
            case 2:
                sCart.loadData();
                ft.show(sCart);
                ft.hide(home);
                break;
            default:
                showToast("程序错误");
                break;
        }
        ft.commit();
    }

    private void setBtn(boolean a, boolean b) {
        btnHome.setSelected(a);
        btnCart.setSelected(b);
    }
    /**
     * 获取购物车总数
     */
    public void getShoppingCartNumber() {
        request(Request.Method.GET, URL.CART.TOTAL_QTY, null, sessionId, tag, 100);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (btnCart.isSelected()) {
            ft = getFragmentManager().beginTransaction();
            setBtn(true, false);
            ft.hide(sCart);
            ft.show(home);
            ft.commit();
            type = 0;
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            exit(MainActivity.this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    @Override
    public void success(int type, JSONObject jsonObject) {

        switch (type) {
            case 100:
                JSONObject data = jsonObject.optJSONObject("data");
                int quantity = data.optInt("quantity");
                System.out.println("quantity===" + quantity);
                if (quantity > 0) {
                    cartSize.setVisibility(View.VISIBLE);
                    cartSize.setText(quantity + "");
                } else {
                    cartSize.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    public void fail() {

    }

    class Broad extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if("ShoppingCartFragment".equals(intent.getAction())){
                System.out.println("===Broad=ShoppingCartFragment");
                type = 2;
            }
        }
    }
}
